.PHONY: default clean
include Config.make

CORE_DIR_LIST := boot memory
SUBDIR_LIST := $(CORE_DIR_LIST) cxx fix pic

default: subdir_rule $(OBJ_PATH)/c.img

$(OBJ_PATH)/c.img: $(OBJ_PATH)/ossym.list $(OBJ_PATH)/trampoline.bin $(OBJ_PATH)/bootmain.bin $(OBJ_PATH)/zeroimage.bin $(OBJ_PATH)/cxxfix.test.elf $(OBJ_PATH)/cxxpic.test.elf $(OBJ_PATH)/fix.elf $(OBJ_PATH)/pic.elf
	cd $(OBJ_PATH) && ./deployOS.sh

$(OBJ_PATH)/ostest.o: $(OBJ_PATH)/cxx/cxx.test.o
	ld -r -o $@ $^
$(OBJ_PATH)/core.o: $(patsubst %, $(OBJ_PATH)/%, $(join $(CORE_DIR_LIST), $(patsubst %, /%.package.o, $(CORE_DIR_LIST))))
	ld -r -o $@ $^
$(OBJ_PATH)/head.o: $(OBJ_PATH)/cxx/cxx.package.o
	ld -r -o $@ $^

$(OBJ_PATH)/core.prep: $(OBJ_PATH)/core.o $(OBJ_PATH)/head.o $(OBJ_PATH)/ostest.o
	ld --eh-frame-hdr -Map $(OBJ_PATH)/core.map -T core.ld -o $@ $^
$(OBJ_PATH)/trampoline.bin: $(OBJ_PATH)/core.prep
	objcopy -O binary $< $@ -j trampoline
$(OBJ_PATH)/bootmain.bin: $(OBJ_PATH)/core.prep
	objcopy -O binary $< $@ -j bootmain
$(OBJ_PATH)/zeroimage.bin: $(OBJ_PATH)/core.prep
	objcopy -O binary $< $@ -j cxx -j zerotest -j text -j data -j bss -j typeinfo -j .eh_frame -j cxxex -j .eh_frame_hdr

$(OBJ_PATH)/cxxfix.test.elf: $(OBJ_PATH)/cxx/cxxfix.test.o $(OBJ_PATH)/ossym.list
	ld --eh-frame-hdr -Map $(OBJ_PATH)/cxxfix.test.map -T fix.ld --just-symbols=$(OBJ_PATH)/ossym.list -o $@ $^
$(OBJ_PATH)/cxxpic.test.elf: $(OBJ_PATH)/cxx/cxxpic.test.o $(OBJ_PATH)/ossym.list
	ld --eh-frame-hdr -shared -Map $(OBJ_PATH)/cxxpic.test.map -T pic.ld --just-symbols=$(OBJ_PATH)/ossym.list -o $@ $^
$(OBJ_PATH)/fix.elf: $(OBJ_PATH)/fix/fix.package.o $(OBJ_PATH)/ossym.list
	ld --eh-frame-hdr -Map $(OBJ_PATH)/fix.map -T fix.ld --just-symbols=$(OBJ_PATH)/ossym.list -o $@ $^
$(OBJ_PATH)/pic.elf: $(OBJ_PATH)/pic/pic.package.o $(OBJ_PATH)/ossym.list
	ld --eh-frame-hdr -shared -Map $(OBJ_PATH)/pic.map -T pic.ld --just-symbols=$(OBJ_PATH)/ossym.list -o $@ $^

# os export symbols.
$(OBJ_PATH)/os_symtab: $(OBJ_PATH)/core.prep
	objcopy -O binary $< $@ -j os_symtab
$(OBJ_PATH)/os_symtab_strings: $(OBJ_PATH)/core.prep
	objcopy -O binary $< $@ -j os_symtab_strings
$(OBJ_PATH)/ossym.list: $(OBJ_PATH)/os_symtab $(OBJ_PATH)/os_symtab_strings
	cd $(OBJ_PATH) && ./symbol.py

clean:
	(cd ../ && make clean prepare)

include Rules.make
